﻿package com.tomvian.maths.areas
{
	import flash.display.DisplayObject;
	import flash.geom.Rectangle;
	import com.tomvian.maths.Vector2D;
	
	/**
	 * DisplayArea
	 * @author Thomas Vian
	 */
	public class DisplayArea extends Area
	{
		//--------------------------------------------------------------------------
		//
		//  Properties
		//
		//--------------------------------------------------------------------------
		
		private var _displayObject:DisplayObject;
		
		//--------------------------------------------------------------------------
		//
		//  Constructor
		//
		//--------------------------------------------------------------------------
		
		public function DisplayArea(displayObject:DisplayObject)
		{
			_displayObject = displayObject;
		}
		
		//--------------------------------------------------------------------------
		//
		//  Methods
		//
		//--------------------------------------------------------------------------
		
		override public function contains(vector:Vector2D):Boolean 
		{ 
			return _displayObject.hitTestPoint(vector.x, vector.y, true);
		}
		
		override public function random():Vector2D 
		{
			if(_displayObject.stage)
			{
				var rectArea:Rectangle = _displayObject.getRect(_displayObject.stage);
				var x:Number = rectArea.x;
				var y:Number = rectArea.y;
				var width:Number = rectArea.width;
				var height:Number = rectArea.height;
				
				var c:uint;
				var randX:Number = Math.random() * width + x;
				var randY:Number = Math.random() * height + y;
				
				while (!_displayObject.hitTestPoint(randX, randY, true) && c++ < 50)
				{
					randX = Math.random() * width + x;
					randY = Math.random() * height + y;
				}
				
				if(c >= 50) return new Vector2D();
				else 		return new Vector2D(randX, randY);
			}
			
			return new Vector2D();
		}
		
		override public function cleanup():void
		{
			_displayObject = null;
		}
	}
}